;
(function(win, $, l) {
    var BASE = {
        redirect_url: function(obj) {
            var index = BASE._dialog({
                type: 'load',
                cont:obj.cont
            });
            if(obj.isIframe && obj.isIframe!=='undefined'){
                $("body").getNiceScrolls({selected:[{".data-content":115}]});
                layer.close(index);
                $(obj.cont).empty().append("<iframe src="+obj.url+" width='100%' frameborder='0' height='100%'></iframe>");
            }else{
                $(obj.cont).empty().load(obj.url, obj.data, function(res, status, xhr) {
                    layer.close(index);
                    if (status !== 'success') {
                        BASE._dialog({
                            msg: BASE.getStatus(status),
                            type: 'alert',
                        });
                    } else {
                        if(xhr.getResponseHeader("session-status") == "timeout"){
                            l.msg("");
                            l.confirm('会话超时,你确定要重新登录吗？', {
                                btn: ['确定'] //按钮
                            }, function(){
                                window.location.href = window.location.origin+"/login"
                            });

                        }else{
                            var o = obj.data;
                            for (var key in o) {
                                $('input[name=' + key + ']').val(o[key]);
                            }
                        }
                    }
                });
            }
        },
        _dialog: function(obj) {
            var src = {
                button: [],
                title: '提示',
                msg: '操作成功',
                type: 'load', //tip:捕获页
                icon: 1
            };
            $.extend(src, obj);
            switch (src.type) {
                case 'load':
                    return l.load(0, { shade: [0.3,'#fff']},$(obj.cont));
                case 'alert':
                    l.alert(src.msg, { icon: '&#xe69c;' });
                    break;
                default:
                    l.open({
                        title: src.title,
                        type: src.type,
                        content: src.msg
                    });
            }
        },
        getStatus: function(status) {
            debugger
            switch (status) {
                case 'notmodified':
                    return '304 not modified';
                case 'error':
                    return '网络异常';
                case 'timeout':
                    return '访问超时';
                case 'parsererror':
                    return 'parser error';
                default:
                    return '系统错误';
            }
        }
    };
    //jquery初始化插件
    $.fn.extend({
        //初始化菜单
        initMenu: function(obj) {
            $("body").getNiceScrolls();
            $(this).find("li").eq(0).find("dl").slideDown().siblings("a").addClass("base-active");
            var _init =$(this).find("li").eq(0).find("dl").find("dt").eq(0).find("a");
            var v_url = $(this).find("li").eq(0).find("dl").find("dt").eq(0).find("a").data("url");
            var o = {
                'cont':'.data-content',
                'url': v_url,
                'data': '',
                'isIframe':_init.data("isiframe")
            };
            //设置二级导航
            _init.data("url") ?(BASE.redirect_url(o),$(".bread-dis li:eq(1) span").text(_init.parents('li').find('a').attr('title'))) : '';

            var src = {
                content: '.data-content'
            };
            var defaults = $.extend(src, obj);
            var $_this = this;
            var $a = $_this.find('a');
            $_this.on('click', 'a', function(e) {
                e.preventDefault();
                var $_this = $(this);
                var o = {
                    'cont': defaults.content,
                    'url': $_this.data('url'),
                    'data': '',
                    'isIframe':$_this.data("isiframe")
                };
                //设置二级导航
                $_this.data("url") ?(BASE.redirect_url(o),$(".bread-dis li:eq(1) span").text($_this.parents('li').find('a').attr('title'))) : '';
            });
        },
        gotoNewLink: function(obj) {
            obj.cont = this;
            if (obj instanceof Object) BASE.redirect_url(obj);
        },
        /**
         * HandBar模板生成
         */
        parseTemplate: function(templateId, data) {
            var myTemplate = Handlebars.compile($("#" + templateId).html());
            // 索引
            Handlebars.registerHelper("addOne", function(index, options) {
                return (index*1) + 1;
            });
            Handlebars.registerHelper('isNull',function(param, options){
                var v_p= '';
                if(!param){
                    v_p = '无';
                }else{
                    v_p = param;
                }
                return v_p;
            });
            Handlebars.registerHelper('getSex',function(param, options){
                var v_p= '';
                if(param=='1'){
                    v_p = '男';
                }else{
                    v_p = '女';
                }
                return v_p;
            });
            Handlebars.registerHelper('getType',function(param, options){
                var v_p= '';
                if(param=='1'){
                    v_p = '菜单';
                }else if(param=='2'){
                    v_p = '系统';
                }else{
                    v_p = '按钮';
                }
                return v_p;
            });
            Handlebars.registerHelper('isNot',function(param, options){
                var html_string = (param===true?"<span class='base-red'>已锁定</span>":"<span class='base-green'>未锁定</span>");
                return new Handlebars.SafeString(html_string);
            });

            Handlebars.registerHelper('isStart',function(param, options){
                var html_string = (param=='0'?"<span class='base-yellow'>保存</span>":"<span class='base-green'>发布</span>");
                return new Handlebars.SafeString(html_string);
            });
            Handlebars.registerHelper('convert',function(param, options){
                var html_string = (param?param:'');
                return new Handlebars.SafeString($(html_string).text());
            });

            Handlebars.registerHelper('cont',function(param, options){
                return new Handlebars.SafeString(param);
            });

            this.html(myTemplate(data));
        },
        getNiceScrolls:function(obj){
            var defaults = {
                selected:[{"#menu":80}],
                bgcolor:"#3B99FC"
            };
            $.extend(defaults, obj);
            defaults.selected.forEach(function(v,i){
                for(var key in v){
                    $(key).height(
                        (document.documentElement.clientHeight
                            || window.innerHeight || window.screen.height)
                        - v[key] + "px");
                    $(key).niceScroll({
                        cursorcolor : defaults.bgcolor,
                        cursoropacitymax : 1,
                        touchbehavior : false,
                        cursorwidth : "5px",
                        cursorborder : "0",
                        autohidemode : false,
                        cursorborderradius : "1px"
                    });
                }
            });

        }
    });
    $.extend({
        //图片预览
        imgView:function(obj){
            var defaults = {
                img_width:'120px',
                img_height:'160px'
            };
            $.extend(defaults,obj);
            if(defaults.fileEle){
                var fileObj = document.getElementById(defaults.fileEle),//获得当前上传文件的file表单
                    viewImg = document.getElementById(defaults.viewImg);//获得
                $(fileObj).on('change',function(){
                    if(fileObj.files && fileObj.files[0]){
                        //火狐下，直接设img属性
                        viewImg.style.display = 'block';
                        viewImg.style.width = defaults.img_width;
                        viewImg.style.height = defaults.img_height;
                        //imgObjPreview.src = docObj.files[0].getAsDataURL();
                        //火狐7以上版本不能用上面的getAsDataURL()方式获取，需要一下方式
                        viewImg.src = window.URL.createObjectURL(fileObj.files[0]);
                    }
                });
            }
        },
        baseEvent: function(obj) {
            var defaults = {
                    listCont:"#data-list",
                    formCont:"#data-form"
                },
                defaults = $.extend(defaults,obj);
            //设置导航三级标题
            $(".bread-dis li:eq(2) span").text($(".banner:eq(0) span").data('title'));
            //返回
            $('#btn_back,#btn_cancel').on('click', function() {
                $(".data-content").gotoNewLink({
                    url: obj.data_list,
                });
            });

            //全选与反选
            $("#selectAll").on('click',function(){
                if($(this).prop("checked")){
                    $("#datalist tr td:nth-child(1) input:checkbox").prop('checked',true);
                }else{
                    $("#datalist tr td:nth-child(1) input:checkbox").prop('checked',false);
                }
            });
            //新增页面
            $("#btn_add").on('click', function() {
                $.clear();
                if(obj.add_is_dialog){
                    layer.open({
                        type: 1,
                        anim: 2,
                        title: "<span class='dialog_title base-zb-info'>"+$("#data-form").data("title")+"</span>",
                        area: ['60%', '50%'],
                        content: $('#data-form'),
                        success:function(layero){
                            var mask = $(".layui-layer-shade");
                            $('.data-content').append(mask);
                        }
                    });
                }else{
                    $(".fixed_pos").css({position:"inherit"});
                    $("#btn_save").show();
                    $("#data-list").hide().siblings("#data-form").show();
                    $("body").getNiceScrolls({selected:[{"#data-form":130}]});
                }
                $("input,select,textarea").val("");
            });
            //详情界面
            $('#datalist').on('click', '.detail,.update', function() {
                var $_this = $(this);
                var my = {
                    url: obj.findBy_url?obj.ctx+obj.findBy_url:obj.ctx+"/com/query",
                    para: {
                        "ID": $(this).data('pkid'),
                        "sid": obj.sid
                    },
                    type:'GET',
                    callback: function(res) {
                        if(obj.add_is_dialog){
                            layer.open({
                                type: 1,
                                anim: 2,
                                title: "<span class='dialog_title base-zb-info'>"+$_this.attr("title")+"</span>",
                                area: ['60%', '50%'],
                                content: $('#data-form'),
                                success:function(layero){
                                    var mask = $(".layui-layer-shade");
                                    $('.data-content').append(mask);
                                }
                            });
                        }else{
                            $("#btn_save").show();
                            $(".fixed_pos").css({position:"inherit"});
                            $("#data-list").hide().siblings("#data-form").show();
                            $("body").getNiceScrolls({selected:[{"#data-form":130}]});
                        }

                        $.setValue(res.data);
                        if($_this.is(".detail")){
                            $("#btn_save").remove();
                            $('input,select,textarea').addClass('oper-no');
                        }
                        var ue = UE.getEditor('container');
                        ue.ready(function() {
                            ue.execCommand('inserthtml', $("#ueditor_textarea_content").val());
                        });
                        var imgPath = $("input[name='imgPath']").val();
                        if(imgPath){
                            $("#fileImg").attr('src','/uploadImg/'+imgPath);
                        }
                    }
                };
                $._NormalRequest(my);
            });

            //删除方法
            $('#datalist').on('click', '.delete', function() {
                var $_this = $(this);
                layer.confirm('你确定要删除吗？', {
                    btn: ['确定','取消']//按钮
                }, function(){
                    var $_id = $_this.data("pkid");
                    if ($_id) {
                        var my = {
                            url: obj.del_url?obj.ctx+obj.del_url:obj.ctx+"/com/delete",
                            para: {
                                ID: $_id,
                                sid: obj.sid
                            },

                            callback: function(res) {
                                if (res.code == '1') {
                                    $(".data-content").gotoNewLink({
                                        url: obj.data_list,
                                    });
                                }
                                layer.msg(res.message);
                            }
                        };
                        $._NormalRequest(my);
                    } else {
                        layer.msg('没有发现主键，无法删除。');
                    }
                });

            });
            //删除全部
            $('#btn_deleteAll').on('click', function() {
                var IDS = $("#datalist input:checked")
                if (IDS.val()) {
                    layer.confirm('你确定要删除选中的吗？', {
                        btn: ['确定','取消']//按钮
                    }, function(){
                        var deleteIDS = IDS.map(function(i,e){
                            return $(e).val();
                        }).get().join(',');
                        var my = {
                            url: obj.del_all_url?obj.ctx+obj.del_all_url:obj.ctx+"/com/deleteAll",
                            para: {
                                IDS: deleteIDS,
                                sid: obj.sid
                            },
                            type:'GET',
                            callback: function(res) {
                                if (res.code == '1') {
                                    $(".data-content").gotoNewLink({
                                        url: obj.data_list,
                                    });
                                }
                                layer.msg(res.message);
                            }
                        };
                        $._NormalRequest(my);
                    });
                }else{
                    layer.msg('请选择后再删除。');
                }
            });
            //查询
            $("#btn_search").on('click', function() {
                obj.pageCurrent='1';
                $.queryList(obj);
            });

            //保存方法
            $('#btn_save').on('click', function() {
                //表单校验
                var isTemp = $(obj.formSelect?"#"+obj.formSelect:"#form").validateForm({
                    msgPosition : 'right'
                });
                //分类处理
                if (isTemp) {
                    var my = {
                        form : obj.formSelect?obj.formSelect:"form",
                        para : {
                            "sid" :obj.sid
                        },
                        url : obj.form_url?obj.ctx+obj.form_url:obj.ctx+"/com/add",
                        callback : function(res) {
                            layer.msg(res.message);
                            if(res.code == '1'){
                                $(".data-content").gotoNewLink({url:obj.data_list});
                            }
                        }
                    };
                    $._FormRequest(my);
                }
            });
            //初始化列表页面
            $.queryList(obj);
        },
        _NormalRequest: function(who) {
            var index = BASE._dialog({
                type: 'load'
            });
            if (who.para) {
                who.para.ts = Math.random();
            }
            $.ajax({
                type: (who.type === undefined || who.type === null) ? "POST" : who.type,
                cache: false,
                url: who.url,
                data: (who.para === undefined || who.para === null) ? {} : who.para,
                dataType: "json",
                async: (who.async === undefined || who.async === null) ? true : false,
                timeout: 30000,
                success: function(res) {
                    layer.close(index);
                    if (who.callback) {
                        who.callback(res);
                    } else {
                        console.log(res.message);
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    BASE._dialog({
                        msg: BASE.getStatus(textStatus),
                        type: 'alert',
                    });
                }
            });
        },
        /**
         * form表单提交数据
         * @param who 请求对象
         */
        _FormRequest: function(who) {
            var index = BASE._dialog({
                type: 'load'
            });
            $("#" + who.form).ajaxSubmit({
                type: "POST",
                url: who.url,
                data: (who.para === undefined || who.para === null) ? {} : who.para,
                dataType: "json",
                success: function(res) {
                    layer.closeAll();
                    if (who.callback) {
                        who.callback(res);
                    } else {
                        console.log(res.message);
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    BASE._dialog({
                        msg: BASE.getStatus(textStatus),
                        type: 'alert',
                    });
                }
            });
        },
        /*
         * 获得URL参数
         */
        getUrlPara: function(paras, isde) {
            if (!isde) {
                isde = "";
            }
            var url = location.href;
            var paraString = url.substring(url.indexOf("?") + 1, url.length).split("&");
            var paraObj = {};
            for (i = 0; j = paraString[i]; i++) {
                paraObj[j.substring(0, j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=") + 1, j.length);
            }
            var returnValue = paraObj[paras.toLowerCase()];
            if (typeof(returnValue) == "undefined") {
                return "";
            } else {
                if (isde == "1") {
                    return decodeURI(returnValue); // 返回解码的数据
                } else {
                    return returnValue; // 返回参数中的原始数据
                }
            }
        },
        //获得数据列表
        queryList: function(obj) {
            //滚动条
            $("body").getNiceScrolls({selected:[{"#list":255},{".data-list_edit":255}]});

            //隐藏表单
            $("#data-list").siblings("#data-form").hide();
            var v_obj = {};
            v_obj.sid = obj.sid;
            //处理参数(除去当前页)
            if(obj.param){
                var v_p = obj.param;
                for(var i = 0,l = v_p.length;i<l;i++){
                    v_obj[v_p[i]] = $("#"+v_p[i]).val();
                }
            }
            var requestAjax = {};
            //分类处理，如果带分页
            if(obj.isPage){
                v_obj.pageCurrent = obj.pageCurrent;
                requestAjax = {
                    url: obj.ctx+obj.pageList_url,
                    para: v_obj,
                    callback: function(res) {
                        $('.datalist').empty();
                        $(".base-message").remove();
                        var code = res.code;
                        var data = res.data;

                        //数据加载完毕图片懒加载
                        if($("img.lazy").length>0){
                            $("img.lazy").lazyload({effect: "fadeIn"});
                        }
                        if(code == '1') {
                            $('#datalist').parseTemplate('tradecent-template',data.content);
                            var pageCount = data.totalPages;
                            var pageCurrent = data.number+1;
                            if(data.number<5){
                                if(pageCount<10){
                                    pagebetween = data.totalPages;
                                }else if(pageCount){
                                    pagebetween = 10;
                                }
                                pageCurrent = 1;
                            }else if(data.number>=5 && data.number<=pageCount){
                                if(pageCount-data.number<10){
                                    pagebetween = pageCount;
                                    pageCurrent = (pageCount-9)<0?1:pageCount-9;
                                }else{
                                    pagebetween = data.number + 10;
                                    pageCurrent = data.number;
                                }
                            }
                            var page_html = "<div class='list-page' id='page_list'><ul><li class='pre' data-pcurrent='1'><i class='iconfont icon-shouye base-blue'></i></li>";
                            for(var i = pageCurrent;i<pagebetween+1;i++){
                                if(i === data.number+1){
                                    page_html += "<li class='pageActive' data-pcurrent="+i+">"+i+"</li>";
                                }else{
                                    page_html += "<li data-pcurrent="+i+">"+i+"</li>";
                                }

                            }
                            page_html += "<li class='next' data-pcurrent="+data.totalPages+"><i class='iconfont icon-shouye base-blue'></i></li><li>共"+data.totalPages+"页/当前第"+(data.number+1)+"页</li><li>共"+data.totalElements+"条</li></ul></div>"	;
                            if($("#list").has('.list-page')){
                                $("#list").find('.list-page').remove();
                                $("#list,.datalist").append(page_html);
                            }else{
                                $("#list,.datalist").append(page_html);
                            }
                            //给分页加载事件
                            $("#page_list").on('click','li',function(){
                                var pageCurrent = $(this).data('pcurrent');
                                obj.pageCurrent = pageCurrent;
                                $.queryList(obj);
                            });
                        } else if (code == '2') {
                            $("#list").find('tbody').empty();
                            $("#page_list").remove();
                            $("#list,.datalist").append("<div class='base-gray center base-message'>" + res.message + "</div>");
                        } else if (code == '0') {
                            layer.msg(res.message);
                        }
                    }
                };
                $._NormalRequest(requestAjax);
            }else{
                if(!obj.ctx || !obj.sid){
                    BASE._dialog({
                        msg:'请检查你的配置项是否正确',
                        type: 'alert',
                    });
                }else{
                    v_obj.sid = obj.sid;
                    requestAjax = {
                        url: obj.ctx+"/com/queryList",
                        para: v_obj,
                        callback: function(res) {
                            $(".base-message").remove();
                            $("#list").find('tbody').empty();
                            var code = res.success;
                            if(code == '1') {
                                $('#datalist').parseTemplate('tradecent-template', res.data);
                            }else if (code == '2') {
                                $("#list").append("<div class='base-gray center base-message'>" + res.message + "</div>");
                            }else if (code == '0') {
                                layer.msg(res.message);
                            }
                        }
                    };
                    $._NormalRequest(requestAjax);
                }
            }
        }
    });
})(window, jQuery, layer);
